﻿using System.Reflection;
using Autofac;
using Md.Api.Model;

namespace Md.Api;
/// <summary>
/// 依赖注入
/// </summary>
public class AutofacModule : Autofac.Module
{
    /// <summary>
    /// 加载注入
    /// </summary>
    /// <param name="builder"></param>
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<ResponseMessageModel>()
            .AsSelf()
            .PropertiesAutowired();
        
        var controllerService = Assembly.Load(new AssemblyName("Md.Api.Controllers"));
        builder.RegisterAssemblyTypes(controllerService)
            .Where(t=>t.Name.EndsWith("Controller"))
            .InstancePerDependency()
            .PropertiesAutowired();

        var utilService = Assembly.Load(new AssemblyName("Md.Util.Service"));
        builder.RegisterAssemblyTypes(utilService)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .AsSelf()
            .PropertiesAutowired();

        var apiService = Assembly.Load(new AssemblyName("Md.Api.Service"));
        builder.RegisterAssemblyTypes(apiService)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .AsSelf()
            .PropertiesAutowired();

        var petapocoRepositories = Assembly.Load(new AssemblyName("Md.Petapoco.Repositories"));
        builder.RegisterAssemblyTypes(petapocoRepositories)
            .Where(t => t.Name.EndsWith("Rep"))
            .AsImplementedInterfaces()
            .AsSelf()
            .PropertiesAutowired();

        var dapperRepositories = Assembly.Load(new AssemblyName("Md.Dapper.Repositories"));
        builder.RegisterAssemblyTypes(dapperRepositories)
            .Where(t => t.Name.EndsWith("Rep"))
            .AsImplementedInterfaces()
            .AsSelf()
            .PropertiesAutowired();

        var redisRepositories = Assembly.Load(new AssemblyName("Md.Redis.Repositories"));
        builder.RegisterAssemblyTypes(dapperRepositories)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .AsSelf()
            .PropertiesAutowired();

        //var redisRepositories = Assembly.Load(new AssemblyName("Md.Redis.Respositories"));
        //builder.RegisterAssemblyTypes(redisRepositories)
        //    .Where(t => t.Name.EndsWith("Rep"))
        //    .AsImplementedInterfaces()
        //    .AsSelf()
        //    .PropertiesAutowired();
    }
}

